let selectedFiles = [];
let folderStructure = {};
let conversionResults = [];

// 文件选择处理
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
document.getElementById('folderInput').addEventListener('change', handleFolderSelect);

// 拖拽处理
const uploadArea = document.getElementById('uploadArea');
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);

function handleFileSelect(event) {
    const files = Array.from(event.target.files);
    processFiles(files, false);
}

function handleFolderSelect(event) {
    const files = Array.from(event.target.files);
    processFiles(files, true);
}

function handleDragOver(event) {
    event.preventDefault();
    uploadArea.classList.add('dragover');
}

function handleDragLeave(event) {
    event.preventDefault();
    uploadArea.classList.remove('dragover');
}

function handleDrop(event) {
    event.preventDefault();
    uploadArea.classList.remove('dragover');
    
    const items = event.dataTransfer.items;
    const files = [];
    let isFolder = false;
    
    // 检查是否拖拽的是文件夹
    for (let item of items) {
        if (item.kind === 'file') {
            const entry = item.webkitGetAsEntry();
            if (entry && entry.isDirectory) {
                isFolder = true;
                // 读取文件夹内容
                readDirectory(entry, files);
                break;
            }
        }
    }
    
    // 如果没有文件夹，处理文件
    if (!isFolder) {
        const droppedFiles = Array.from(event.dataTransfer.files);
        processFiles(droppedFiles, false);
    }
}

function readDirectory(dirEntry, files) {
    const reader = dirEntry.createReader();
    
    function readEntries() {
        reader.readEntries((entries) => {
            if (entries.length === 0) {
                processFiles(files, true);
                return;
            }
            
            for (let entry of entries) {
                if (entry.isFile) {
                    entry.file((file) => {
                        files.push(file);
                    });
                } else if (entry.isDirectory) {
                    readDirectory(entry, files);
                }
            }
            
            readEntries();
        });
    }
    
    readEntries();
}

function processFiles(files, isFolder) {
    // 过滤支持的音频文件
    const audioFiles = files.filter(file => {
        const extension = file.name.split('.').pop().toLowerCase();
        return ['m4a', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(extension);
    });
    
    if (audioFiles.length === 0) {
        alert('未找到支持的音频文件');
        return;
    }
    
    selectedFiles = audioFiles;
    
    // 如果是文件夹，构建目录结构
    if (isFolder) {
        buildFolderStructure(audioFiles);
    }
    
    // 显示文件列表
    displayFileList();
    
    // 显示转换按钮
    document.getElementById('convertButton').style.display = 'block';
    document.getElementById('progressSection').style.display = 'none';
    document.getElementById('downloadSection').style.display = 'none';
}

function buildFolderStructure(files) {
    folderStructure = {};
    
    files.forEach(file => {
        // 从webkitRelativePath获取相对路径
        const path = file.webkitRelativePath || file.name;
        const pathParts = path.split('/');
        
        if (pathParts.length > 1) {
            const folderName = pathParts[0];
            if (!folderStructure[folderName]) {
                folderStructure[folderName] = [];
            }
            folderStructure[folderName].push(file);
        }
    });
}

function displayFileList() {
    const fileItemsContainer = document.getElementById('fileItems');
    fileItemsContainer.innerHTML = '';
    
    selectedFiles.forEach((file, index) => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        fileItem.innerHTML = `
            <div class="file-name">
                <i class="fas fa-music me-2"></i>
                ${file.name}
                <small class="text-muted d-block">${formatFileSize(file.size)}</small>
            </div>
            <span class="file-status status-pending" id="status-${index}">等待转换</span>
        `;
        fileItemsContainer.appendChild(fileItem);
    });
    
    document.getElementById('fileList').style.display = 'block';
}

function convertFiles() {
    if (selectedFiles.length === 0) return;
    
    // 显示进度区域
    document.getElementById('progressSection').style.display = 'block';
    document.getElementById('convertButton').style.display = 'none';
    
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    
    let completedCount = 0;
    const totalFiles = selectedFiles.length;
    
    // 逐个转换文件
    selectedFiles.forEach((file, index) => {
        updateFileStatus(index, 'converting', '转换中...');
        
        const formData = new FormData();
        formData.append('file', file);
        
        // 如果是文件夹模式，添加文件夹信息
        if (Object.keys(folderStructure).length > 0) {
            const folderName = getFolderName(file);
            if (folderName) {
                formData.append('folderName', folderName);
            }
        }
        
        fetch('/api/audio/convert', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const convertedFilename = data.convertedFilename || 'converted.mp3';
                updateFileStatus(index, 'completed', `转换完成: ${convertedFilename}`);
                conversionResults.push({
                    originalFile: file.name,
                    convertedFile: data.convertedFile,
                    convertedFilename: convertedFilename,
                    folderName: getFolderName(file)
                });
            } else {
                updateFileStatus(index, 'error', '转换失败');
            }
            
            completedCount++;
            const progress = (completedCount / totalFiles) * 100;
            progressBar.style.width = progress + '%';
            progressText.textContent = `转换进度: ${completedCount}/${totalFiles} (${Math.round(progress)}%)`;
            
            // 所有文件转换完成
            if (completedCount === totalFiles) {
                setTimeout(() => {
                    document.getElementById('progressSection').style.display = 'none';
                    document.getElementById('downloadSection').style.display = 'block';
                    
                    // 设置下载链接
                    const downloadBtn = document.getElementById('downloadBtn');
                    downloadBtn.onclick = () => {
                        downloadAllFiles();
                    };
                }, 1000);
            }
        })
        .catch(error => {
            console.error('转换失败:', error);
            updateFileStatus(index, 'error', '转换失败');
            completedCount++;
        });
    });
}

function updateFileStatus(index, status, text) {
    const statusElement = document.getElementById(`status-${index}`);
    if (statusElement) {
        statusElement.className = `file-status status-${status}`;
        statusElement.textContent = text;
    }
}

function getFolderName(file) {
    if (file.webkitRelativePath) {
        const pathParts = file.webkitRelativePath.split('/');
        return pathParts.length > 1 ? pathParts[0] : null;
    }
    return null;
}

function downloadAllFiles() {
    // 创建ZIP文件下载
    if (conversionResults.length === 0) {
        alert('没有可下载的文件');
        return;
    }
    
    // 调用后端API创建ZIP文件
    fetch('/api/audio/download-all', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            files: conversionResults
        })
    })
    .then(response => {
        if (response.ok) {
            return response.blob();
        }
        throw new Error('下载失败');
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'converted_audio_files.zip';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    })
    .catch(error => {
        console.error('下载失败:', error);
        alert('下载失败，请重试');
    });
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
} 